package edu.zut.cs.network.dao.service.runnable;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.OutputStreamWriter;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.commons.dbcp.PoolableCallableStatement;
import org.apache.commons.io.output.FileWriterWithEncoding;

import edu.zut.cs.network.base.BaseMainCase;
import edu.zut.cs.network.entity.Book;

public class InnerWriter extends BaseMainCase implements Runnable{
	/** 阻塞队列 */
	private BlockingQueue<List<Book>> blockingQueue;
    /** 输出文件名 */
    private String outputFilePath;
    private final ReentrantLock lock = new ReentrantLock();
	/** 结束标识 */
    private static final List<Book> END = new ArrayList<>();
    
    public InnerWriter() {
		super();
	}
	public InnerWriter(BlockingQueue<List<Book>> blockingQueue, String outputFilePath) {
		super();
		this.blockingQueue = blockingQueue;
		this.outputFilePath = outputFilePath;
	}
	@Override
	public void run() {
		
		List<Book> dataGroup = blockingQueue.poll();
		if (dataGroup == null) {
		return;
		}
		// 读取到结束标识， 重新入队
		if (dataGroup.isEmpty()) {
		blockingQueue.add(END);
		return;
		}

        byte[] bs={(byte)0xef,(byte)0xbb,(byte)0xbf};//  UTF-8的 编码  默认无BOM 此行写入文件头变带BOM头	
        try {
        	//FileWriterWithEncoding out = new FileWriterWithEncoding(outputFilePath, "UTF-8", true);
        	BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFilePath,true), "UTF-8"));
        	out.write(new String(bs));//写入BOM头,防止乱码
        	lock.lock();
        	for (Book i : dataGroup) {
            	out.write(i.getBookName());
				out.write(",");
				out.write(i.getPosition());
				out.write(",");
				out.write(i.getNumber());
				out.write(",");
				out.write(Long.toString(i.getId()));
				out.write("\n");
				
            }
            out.flush();
            out.close();
            logger.info(Thread.currentThread().getName()+"写入成功");
        } catch (Exception e) {
            logger.error(e.getMessage());
        }finally {
			lock.unlock();
		}
	}

}
